import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { cloneDeep } from 'lodash-es'

// 数据项接口定义
export interface DataItem {
  id: string
  name: string
  type: 'string' | 'number' | 'boolean' | 'array' | 'object'
  value: any
  description?: string
}

// 数据池接口定义
export interface DataPool {
  items: DataItem[]
}

// 定义数据池状态管理
export const useDataPoolStore = defineStore('dataPool', () => {
  // 数据池配置
  const dataPool = ref<DataPool>({
    items: []
  })

  // 历史记录 - 用于撤销/重做
  const history = ref<DataPool[]>([])
  const historyIndex = ref(-1)
  const maxHistoryLength = 20

  // 获取数据项
  const getDataItemById = (id: string): DataItem | undefined => {
    return dataPool.value.items.find(item => item.id === id)
  }

  // 获取数据项值
  const getDataItemValue = (id: string): any => {
    const item = getDataItemById(id)
    return item ? item.value : undefined
  }

  // 添加数据项
  const addDataItem = (item: DataItem) => {
    // 保存历史记录
    saveHistory()

    // 检查是否已存在同名数据项
    const existingIndex = dataPool.value.items.findIndex(i => i.name === item.name)
    if (existingIndex >= 0) {
      // 如果存在，则更新
      dataPool.value.items[existingIndex] = item
    } else {
      // 如果不存在，则添加
      dataPool.value.items.push(item)
    }
  }

  // 更新数据项
  const updateDataItem = (id: string, updates: Partial<DataItem>) => {
    // 保存历史记录
    saveHistory()

    const index = dataPool.value.items.findIndex(item => item.id === id)
    if (index >= 0) {
      dataPool.value.items[index] = { ...dataPool.value.items[index], ...updates }
    }
  }

  // 删除数据项
  const removeDataItem = (id: string) => {
    // 保存历史记录
    saveHistory()

    const index = dataPool.value.items.findIndex(item => item.id === id)
    if (index >= 0) {
      dataPool.value.items.splice(index, 1)
    }
  }

  // 保存历史记录
  const saveHistory = () => {
    // 如果当前不是最新状态，则删除当前索引之后的历史记录
    if (historyIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, historyIndex.value + 1)
    }

    // 添加当前状态到历史记录
    history.value.push(cloneDeep(dataPool.value))
    
    // 限制历史记录长度
    if (history.value.length > maxHistoryLength) {
      history.value.shift()
    } else {
      historyIndex.value++
    }
  }

  // 撤销操作
  const undo = () => {
    if (historyIndex.value > 0) {
      historyIndex.value--
      dataPool.value = cloneDeep(history.value[historyIndex.value])
    }
  }

  // 重做操作
  const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++
      dataPool.value = cloneDeep(history.value[historyIndex.value])
    }
  }

  // 导出数据池为JSON
  const exportJSON = () => {
    return JSON.stringify(dataPool.value, null, 2)
  }

  // 导入数据池
  const importJSON = (json: string) => {
    try {
      const data = JSON.parse(json) as DataPool
      dataPool.value = data
      // 重置历史记录
      history.value = [cloneDeep(data)]
      historyIndex.value = 0
      return true
    } catch (error) {
      console.error('导入JSON失败:', error)
      return false
    }
  }

  // 获取所有数据项
  const getAllDataItems = computed(() => {
    return dataPool.value.items
  })

  return {
    dataPool,
    getAllDataItems,
    getDataItemById,
    getDataItemValue,
    addDataItem,
    updateDataItem,
    removeDataItem,
    undo,
    redo,
    exportJSON,
    importJSON
  }
})